#include "stdafx.h"
#include "Message.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>

Message::Message() : m_bodyLength(0)
{}

Message::Message( const Message& message ): m_bodyLength(message.GetBodyLength())
{
   memset(m_data, 0, max_body_length * sizeof(char));
   memcpy(m_data, message.GetData(), m_bodyLength + header_length);
}

Message::~Message()
{

}

bool Message::DecodeHeader()
{
   using namespace std; // For strncat and atoi.
   char header[header_length + 1] = "";
   strncat_s(header, header_length + 1, m_data, header_length);
   m_bodyLength = atoi(header);
   if (m_bodyLength > 0)
      return true;
   return false;
}

void Message::EncodeHeader()
{
   using namespace std; // For sprintf and memcpy.
   char header[header_length + 1] = "";
   sprintf_s(header, header_length + 1, "%4d", m_bodyLength);
   memcpy(m_data, header, header_length);
}

void Message::SetBody( const char * body )
{
   if (body)
   {
      memcpy(m_data + header_length, body, m_bodyLength);
   }
}

const char* Message::GetBody() const
{
   return m_data + header_length;
}

char* Message::GetBody()
{
   return m_data + header_length;
}

size_t Message::GetBodyLength() const
{
   return m_bodyLength;
}

void Message::SetBodyLength( const size_t newSize )
{
   if (newSize > 0 || newSize < max_body_length)
      m_bodyLength = newSize;
   else
      m_bodyLength = max_body_length - 1;
}

size_t Message::GetLength() const
{
   return header_length + m_bodyLength;
}

const char* Message::GetData() const
{
   return m_data;
}

char* Message::GetData()
{
   return m_data;
}